package com.topscomm.base.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.base.pojo.BaseTeamUserEntity;
import com.topscomm.base.service.IBaseCboUserExtendService;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.base.service.IBaseTeamUserService;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.pojo.CboUserRoleEntity;
import com.topscomm.cbo.service.ICboUserRoleService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;

/**
 * @author: shenyouyi
 * @date: 2020-08-29
 * @description:
 * @modify:
 */
@Service("baseCboUserExtendService")
@Scope("singleton")
public class BaseCboUserExtendService implements IBaseCboUserExtendService {

    @Autowired
    private ICboUserService cboUserService;
    @Autowired
    private ICboUserRoleService cboUserRoleService;
    @Autowired
    private IBaseTeamUserService baseTeamUserService;
    @Autowired
    private IBasePermissionManageService basePermissionManageService;

    // QuartzUser用户工号系统编码
    private static final String Quartz_User_Code = "QuartzUserCode";

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-08-29
     * @param: roleIds
     * @description: 根据角色ID查询用户信息(包含部门Code和组织Code)
     * @modify:
     */
    @Override
    public List<Map<String, Object>> searchUserByRoleIds(String roleIds) {
        List<Map<String, Object>> userMapList = new ArrayList<>();
        String[] roleidArray = roleIds.split(",");
        StringBufferProxy idParam = new StringBufferProxy();
        for (String roleid : roleidArray) {
            idParam.appendSingle("{0},", roleid);
        }
        if (idParam.length() > 0) {
            idParam = idParam.substring(0, idParam.length() - 1);
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(CboUserRoleEntity.FieldRoleid + " in ({0})", idParam.toString());
        List<String> queryFields = new ArrayList<>();
        queryFields.add(CboUserRoleEntity.FieldUserid);
        List<Map<String, Object>> userIdMapList = cboUserRoleService.queryMapFieldsByWhere(sql.toString(), queryFields);
        List<String> userIdList = new ArrayList<>();
        userIdMapList.stream()
                .forEach(userIdMap -> userIdList.add(userIdMap.get(CboUserRoleEntity.FieldUserid).toString()));
        idParam.clear();
        for (String userId : userIdList) {
            idParam.appendSingle("{0},", userId);
        }
        if (idParam.length() > 0) {
            idParam = idParam.substring(0, idParam.length() - 1);
            sql.clear();
            sql.appendSingle(" id  in ({0}) and enabled = 1", idParam.toString());
            userMapList = this.basePermissionManageService.queryMapByWhere(sql.toString(), "queryUserInfo");
        }
        return userMapList;
    }

    /**
     * @param teamids
     * @return
     * @description: 查询团队对应的用户数量
     * @author: wanghongwei
     * @date: 2020-11-3 21:50:26
     * @modify:
     */
    @Override
    public List<Map<String, Object>> searchUsersByTeamIds(String teamids) {
        List<Map<String, Object>> userMapList = new ArrayList<>();
        String[] teamidArray = teamids.split(",");
        StringBufferProxy idParam = new StringBufferProxy();
        for (String teamid : teamidArray) {
            idParam.appendSingle("{0},", teamid);
        }
        if (idParam.length() > 0) {
            idParam = idParam.substring(0, idParam.length() - 1);
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(BaseTeamUserEntity.FieldTeamid + " in ({0})", idParam.toString());
        List<String> queryFields = new ArrayList<>();
        queryFields.add(BaseTeamUserEntity.FieldUsercode);
        List<Map<String, Object>> userCodeMapList = this.baseTeamUserService.queryMapFieldsByWhere(sql.toString(),
                queryFields);
        List<String> userCodeList = new ArrayList<>();
        userCodeMapList.stream()
                .forEach(userCodeMap -> userCodeList.add(userCodeMap.get(BaseTeamUserEntity.FieldUsercode).toString()));
        StringBufferProxy codeParam = new StringBufferProxy();
        for (String userCode : userCodeList) {
            codeParam.appendSingle("'{0}',", userCode);
        }
        if (codeParam.length() > 0) {
            codeParam = codeParam.substring(0, codeParam.length() - 1);
            sql.clear();
            sql.appendSingle(" code in ({0}) and enabled=1", codeParam.toString());
            userMapList = this.basePermissionManageService.queryMapByWhere(sql.toString(), "queryUserInfo");
        }
        return userMapList;
    }

    /**
     * @param userCodes
     * @return
     * @description: 根据用户Code查询用户其他信息
     * @author: wanghongwei
     * @date: 2020-11-3 22:06:47
     * @modify:
     */
    @Override
    public List<Map<String, Object>> searchUsersByUserCodes(String userCodes) {
        List<Map<String, Object>> userMapList = new ArrayList<>();
        if (!StrUtil.isEmpty(userCodes)) {
            String codeParam = new ArrayList<>(Arrays.asList(userCodes.split(","))).stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" code in ({0}) and enabled = 1", codeParam);
            userMapList = this.basePermissionManageService.queryMapByWhere(sql.toString(), "queryUserInfo");
        }
        return userMapList;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-08-25
     * @param: deptIds
     * @description: 根据部门编码获取用户信息(包含部门Code和组织Code)
     * @modify:
     */
    @Override
    public List<Map<String, Object>> searchUsersByDeptCodes(String deptCodes) {
        String sql = this.spellSearchUsersByDeptCodesSQL(deptCodes);
        List<Map<String, Object>> userMapList = this.basePermissionManageService.queryMapByWhere(sql, "queryUserInfo");
        return userMapList;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-08-31
     * @param: roleIds
     * @description: 查询角色是否有对应的用户
     * @modify:
     */
    @Override
    public boolean searchHaveUserByRoleIds(String roleIds) {
        int userCount = this.searchUserCountByRoleIds(roleIds);
        return userCount > 0;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-08-31
     * @param: deptcodes
     * @description: 查询部门是否有对应的用户
     * @modify:
     */
    @Override
    public boolean searchHaveUsersByDeptCodes(String deptCodes) {
        // 未选择部门
        if (StringUtil.isEmpty(deptCodes)) {
            return false;
        }
        String sql = this.spellSearchUsersByDeptCodesSQL(deptCodes);
        int userCount = cboUserService.getCount(sql);
        return userCount > 0;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-09-04
     * @param: roleIds
     * @description: 查询角色对应的用户数量
     * @modify:
     */
    @Override
    public int searchUserCountByRoleIds(String roleIds) {
        // 未选择角色
        if (StringUtil.isEmpty(roleIds)) {
            return 0;
        }
        String[] roleidArray = roleIds.split(",");
        StringBufferProxy idParam = new StringBufferProxy();
        for (String roleid : roleidArray) {
            idParam.appendSingle("{0},", roleid);
        }
        if (idParam.length() > 0) {
            idParam = idParam.substring(0, idParam.length() - 1);
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(CboUserRoleEntity.FieldRoleid + " in ({0})", idParam.toString());
        List<String> queryFields = new ArrayList<>();
        queryFields.add(CboUserRoleEntity.FieldUserid);
        List<Map<String, Object>> userIdMapList = cboUserRoleService.queryMapFieldsByWhere(sql.toString(), queryFields);
        List<String> userIdList = new ArrayList<>();
        userIdMapList.stream()
                .forEach(userIdMap -> userIdList.add(userIdMap.get(CboUserRoleEntity.FieldUserid).toString()));
        idParam.clear();
        for (String userId : userIdList) {
            idParam.appendSingle("{0},", userId);
        }
        if (idParam.length() > 0) {
            idParam = idParam.substring(0, idParam.length() - 1);
        }
        sql.clear();
        sql.appendSingle(" id in ({0}) and enabled = 1", idParam.toString());
        int userCount = cboUserService.getCount(sql.toString());
        return userCount;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-09-04
     * @param: deptCodes
     * @description: 查询部门对应的用户数量
     * @modify:
     */
    @Override
    public int searchUserCountByDeptCodes(String deptCodes) {
        // 未选择部门
        if (StringUtil.isEmpty(deptCodes)) {
            return 0;
        }
        String sql = this.spellSearchUsersByDeptCodesSQL(deptCodes);
        int userCount = cboUserService.getCount(sql);
        return userCount;
    }

    /**
     * @return
     * @author: shenyouyi
     * @date: 2020-09-01
     * @param: deptcodes
     * @description: 拼接根据部门编码查询用户SQL
     * @modify: chengengwei
     */
    private String spellSearchUsersByDeptCodesSQL(String deptCodes) {
        String[] deptCodeArray = deptCodes.split(",");
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("{0} = {1} and exists (select 1 from {2} where (", CboUserEntity.FieldEnabled, 1,
                CboDeptEntity.tableName);
        for (String dptCode : deptCodeArray) {
            sql.appendSingle(CboDeptEntity.tableName + "." + CboDeptEntity.FieldCode + " like '{0}%' or ", dptCode);
        }
        if (sql.length() > 1) {// 把最后一个or去掉
            sql = sql.substring(0, sql.length() - 4);
            sql.appendSingle(")");
        }
        sql.appendSingle(" and {0}.{1} = {2}", CboDeptEntity.tableName, CboDeptEntity.FieldEnabled, 1);
        sql.appendSingle(" and {0}.{1} = {2}.{3})", CboDeptEntity.tableName, CboDeptEntity.FieldId,
                CboUserEntity.tableName, CboUserEntity.FieldDeptid);
        return sql.toString();
    }
}
